<template>
  <span>
    <el-button type="success" size="medium" @click="dialogVisible = true">批量同步</el-button>
    <el-dialog
      title="批量增加门店产品"
      :visible.sync="dialogVisible"
      width="80%"
    >
      <div>
        <el-select v-model="storeId" filterable placeholder="请选择">
          <el-option
            v-for="item in stores"
            :key="item.key"
            :label="item.label"
            :value="item.key"
          />
        </el-select>
        <el-button style="margin-left:10px" @click="submit">同步</el-button>
      </div>
    </el-dialog>
  </span>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      stores: [],
      storeId: ''
    }
  },
  created() {
    this.getStores()
  },
  methods: {
    getStores() {
      this.storeIds = []
      this.axios.get(`/manage/stores`, { params: {
        '@display': `{
        'key': 'entity.getId()',
        'label': 'entity.getName()'
      }`
      }}).then((res) => {
        console.log('res', res)
        this.stores = res.data
      })
    },
    submit() {
      if (this.storeId === '' || this.storeId <= 0) {
        this.$message.error('请选择需要同步物料的门店！')
      } else {
        const loading = this.$loading({
          lock: true,
          text: '同步中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.axios.get(`/manage/stocks`, {
          params: {
            '@filter': `entity.getStore().getId() == ${this.storeId} && entity.getMaterial()`,
            limit: 10000
          }
        }).then((res) => {
          // 先查已经有的
          const stocks = res.data
          this.axios.get(`/manage/materials`, {
            params: { limit: 10000 }
          }).then((res) => {
            // 再查所有物料
            const materials = res.data
            // 循环物料，如果无的，放到新增数组里面
            const storeStocks = []
            for (const m of materials) {
              let had = false
              if (stocks.length > 0) {
                for (const s of stocks) {
                  if (s.material.id === m.id) {
                    had = true
                  }
                }
              }
              if (had === false) {
                storeStocks.push({
                  store: this.storeId,
                  material: m.id,
                  remains: 0,
                  currentSingleCost: 0,
                  threshold: 0
                })
              }
            }
            if (storeStocks.length > 0) {
              this.axios.post(`/manage/stocks`, storeStocks).then((res) => {
                this.$message.success('同步成功！')
                this.dialogVisible = false
                loading.close()
              })
            } else {
              this.$message.error('没有需要同步的物料库存')
              loading.close()
            }
          })
        })
      }
    }
  }
}
</script>
